<template>
    <div class="app-container">
        <!-- 顶部功能 -->
        <div class="filter-container" style="margin-bottom: 15px">
            <!-- 预约名输入 -->
            <el-input v-model="queryParam.seatNumber" placeholder="座位编号" style="width: 200px" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <br /><br />
            <!-- <el-button class="filter-item" style="margin-left: 10px; font-size: 18px" type="primary" size="small"
                @click="handleCreate">
                <i class="iconfont icon-r-add" style="font-size: 22px"></i>
                添加预约
            </el-button> -->
        </div>

        <!--弹出框-->
        <el-dialog :title="formTitle" :visible.sync="dialogFormVisible" width="30%">
            <!--普通表单-->
            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px">
                <el-form-item label="编号" prop="title">
                    <el-input v-model="form.seatNumber"></el-input>
                </el-form-item>
                <el-form-item label="位置" prop="location">
                    <el-input v-model="form.location"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="title">
                    <el-input v-model="form.username" :disabled="updateStatus"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false" style="font-size: 18px">
                    <i class="iconfont icon-r-left" style="font-size: 22px"></i>
                    取 消</el-button>
                <el-button type="primary" @click="submitForm" style="font-size: 18px">
                    <i class="iconfont icon-r-yes" style="font-size: 22px"></i>
                    确 定</el-button>
            </div>
        </el-dialog>

        <!--数据表格-->
        <el-table ref="multipleTable" :data="tableData" size="small" border style="width: 100%">
            <el-table-column fixed type="selection" width="55">
            </el-table-column>
            <el-table-column fixed prop="id" label="序号" width="100">
            </el-table-column>
            <el-table-column prop="seatNumber" label="座位编号" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="location" label="位置" show-overflow-tooltip></el-table-column>
            <el-table-column prop="username" label="用户名" show-overflow-tooltip></el-table-column>
            <el-table-column prop="reserveStatus" label="预约状态" :formatter="formatReserveStatus" show-overflow-tooltip>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="240">
                <template slot-scope="scope">
                    <el-button @click="handleUpdate(scope.row)" type="primary" size="small" style="font-size: 18px">
                        <i class="iconfont icon-r-edit" style="font-size: 22px"></i>
                        编辑</el-button>
                    <el-button @click="handleDelete(scope.row, scope.$index)" type="danger" size="small"
                        style="font-size: 18px">
                        <i class="iconfont icon-r-delete" style="font-size: 22px"></i>
                        删除</el-button>
                    <el-button @click="handleUser(scope.row, 2, scope.$index)" type="danger" size="small"
                        style="font-size: 18px">
                        <i class="iconfont icon-check" style="font-size: 22px"></i>
                        通过</el-button>
                    <!-- <el-button @click="handleUser(scope.row,3, scope.$index)" type="danger" size="small"
                        style="font-size: 18px">
                        <i class="iconfont icon-check" style="font-size: 22px"></i>
                        使用</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!--分页条-->
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page.sync="queryParam.page" :page-sizes="[5, 10, 20, 50]" :page-size="queryParam.limit"
            layout="total, sizes, prev, pager, next, jumper" :total="recordTotal" style="margin-top: 15px">
        </el-pagination>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import waves from "@/directive/waves"; // waves directive


import {
    getCount,
    querySeats,
    querySeatsByPage,
    addSeat,
    deleteSeat,
    deleteSeats,
    updateSeat,
    handleStatus
} from "@/api/seat";

export default {
    name: "Bookinfo",
    directives: { waves },
        data() {
        return {
            // 表格数据
            tableData: [],
            // 记录总数
            recordTotal: 0,
            // 查询参数
            queryParam: {
                page: 1,
                limit: 10,
                seatNumber: null,
            },
            // 对话框表单显示
            dialogFormVisible: false,
            // 表单类型（添加数据:0,修改数据:1）
            updateStatus:false,
            formType: 0,
            // 表单数据
            form: {
                seatId: null,
                title: "",
                content: "",
            },
            rules: {
                // seatname: [
                //     {
                //         required: true,
                //         message: "请输入预约名",
                //         trigger: "blur",
                //     },
                // ],
            },
        };
    },
    mounted() {

    },

    computed: {
        // 获得seat信息
        // ...mapGetters(["id", "name", "roles"]),
        // 通过表单类型计算表单标题
        formTitle() {
            return this.formType === 0 ? "添加记录" : "修改记录";
        },
    },
    // 创建后
    created() {
        // 从服务器获取数据表格第一页的信息
        querySeatsByPage(this.queryParam).then((res) => {
            console.log("首页数据获取成功", res);
            this.tableData = res.data;
            this.recordTotal = res.count;
            ;
        });
    },
    methods: {
        // 分页大小改变监听
        handleSizeChange(curSize) {
            const params = this.queryParam;
            params.limit = curSize;
            querySeatsByPage(params).then((res) => {
                console.log("分页数据获取成功 ", res);
                this.tableData = res.data;
                this.recordTotal = res.count;
                ;
            });
        },

        // 点击分页监听方法
        handleCurrentChange(curPage) {
            const params = this.queryParam;
            params.page = curPage;
            querySeatsByPage(params).then((res) => {
                console.log("分页数据获取成功", res);
                this.tableData = res.data;
                this.recordTotal = res.count;
                ;
            });
        },

        // 搜索
        handleFilter() {
            this.queryParam.page = 1;
            querySeatsByPage(this.queryParam).then((res) => {
                if (res.code === 0) {
                    this.tableData = res.data;
                    this.recordTotal = res.count;
                }
                ;
            });
        },

        // 显示全部
        handleShowAll() {
            this.queryParam.page = 1;
            this.queryParam.seatNumber = null;
            querySeatsByPage(this.queryParam).then((res) => {
                if (res.code === 0) {
                    this.tableData = res.data;
                    this.recordTotal = res.count;
                }
                ;
            });
        },

        // 点击添加记录
        handleCreate() {
            // 表单是添加状态
            this.formType = 0;
            this.updateStatus=false;
            // 将空数据置入form
            this.form = {
                id: null,
                seatNumber: "",
                location: '',
                username: '',
            };
            // 显示表单框
            this.dialogFormVisible = true;
        },

        // 点击编辑记录
        handleUpdate(row) {
            // 表单是编辑状态
            this.formType = 1;
            this.updateStatus=true;
            // 将行数据置入form
            this.form = {
                seatId: row.id,
                seatNumber: row.seatNumber,
                location: row.location,
                username: row.username,
            };
            // 显示表单框
            this.dialogFormVisible = true;
        },

        handleUser(row,status, index) {
            console.log("index= ", index);
            console.log("row= ", row);
            if (status == 3 && row.reserveStatus !== 2) {
                this.$message({
                    message: '当前还未预约或者未预约成功',
                    type: 'warning'
                });
                return;

            }
            if (status == 2 && row.reserveStatus !== 1) {
                this.$message({
                    message: '当前预约未处于预约中状态',
                    type: 'warning'
                });
                return;

            }
            this.$confirm("确定要使用这个座位吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                row.reserveStatus=status;
                handleStatus(row).then((res) => {
                    if(res===1){
                        this.$message.success("使用成功");
                    }

                    // if (res === 1) {
                    //     this.$message.success("删除记录成功");
                    //     this.tableData.splice(index, 1);
                    //     // 如果删完了，获取上一页
                    //     if (this.tableData.length === 0) {
                    //         this.queryParam.page = this.queryParam.page - 1;
                    //         this.handleCurrentChange(this.queryParam.page);
                    //     }
                    // } else if (res === -1) {
                    //     this.$message.error(
                    //         "待删除的预约存在图书借阅信息，请先删除该预约所有的借阅信息后再尝试删除预约"
                    //     );
                    // } else if (res === -2) {
                    //     this.$message.error("admin账户无法删除");
                    // } else {
                    //     this.$message.error("删除记录失败");
                    // }
                });
            });
            // 显示表单框
            // this.dialogFormVisible = true;
        },

        // 添加和更新的提交表单
        submitForm() {
            if (this.formType === 0) {
                if (this.form.username === '' || this.form.username == null) {
                    this.$message({
                        message: '用户名必须填',
                        type: 'warning'
                    });
                    return;
                }
                if (this.form.seatNumber === '' || this.form.seatNumber == null) {
                    this.$message({
                        message: '座位编号必须填',
                        type: 'warning'
                    });
                    return;
                }
                // 添加记录
                this.form.reserveStatus = 1;
                addSeat(this.form).then((res) => {
                    if (res === 1) {
                        this.$message.success("添加记录成功");
                        // 跳转到末尾
                        getCount().then((res) => {
                            console.log("res= ",res);
                            this.recordTotal = res.data;
                            this.queryParam.page = Math.ceil(
                                this.recordTotal / this.queryParam.limit
                            );
                            this.handleCurrentChange(this.queryParam.page);
                        });
                    } else if (res === -1) {
                        this.$message.error("不存在当前用户");
                        return;
                    } else {
                        this.$message.error("添加记录失败");
                    }
                    this.dialogFormVisible = false; // 关闭对话框
                });
            } else if (this.formType === 1) {
                //更新记录
                updateSeat(this.form).then((res) => {
                    if (res === 1 || res === 1) {
                        this.$message.success("更新记录成功");
                        this.handleCurrentChange(this.queryParam.page);
                    } else {
                        this.$message.error("更新记录失败");
                    }
                    this.dialogFormVisible = false; // 关闭对话框
                });
            }
        },

        // 删除记录
        handleDelete(row, index) {
            this.$confirm("确定要删除该条记录吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                deleteSeat(row).then((res) => {
                    if (res === 1) {
                        this.$message.success("删除记录成功");
                        this.tableData.splice(index, 1);
                        // 如果删完了，获取上一页
                        if (this.tableData.length === 0) {
                            this.queryParam.page = this.queryParam.page - 1;
                            this.handleCurrentChange(this.queryParam.page);
                        }
                    } else if (res === -1) {
                        this.$message.error(
                            "待删除的预约存在图书借阅信息，请先删除该预约所有的借阅信息后再尝试删除预约"
                        );
                    } else if (res === -2) {
                        this.$message.error("admin账户无法删除");
                    } else {
                        this.$message.error("删除记录失败");
                    }
                });
            });
        },

        // 删除一些
        handleDeleteSome() {
            this.$confirm("确定要删除这些记录吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                // 获取选中的对象数组
                const items = this.$refs.multipleTable.selection;
                deleteSeats(items).then((res) => {
                    if (res > 0) {
                        this.$message.success("删除" + res + "条记录成功");
                        if (this.tableData.length === res) {
                            //如果本页内容全部删光了
                            //当前页为上一页
                            if (this.queryParam.page !== 0) {
                                this.queryParam.page = this.queryParam.page - 1;
                            }
                        }
                        // 重载当前页
                        this.handleCurrentChange(this.queryParam.page);
                    } else {
                        this.$message.error("删除记录失败");
                    }
                });
            });
        },
        formatReserveStatus(row, column, cellValue) {
            const statusMap = {
                0: '可预约',
                1: '预约中',
                2: '已预约',
                3: '已使用',
            };
            return statusMap[cellValue] || cellValue; // 默认显示原值（如果未匹配）
        }
    },

};
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 150px;
    height: 200px;
    display: block;
}
</style>
